package com.ht.serviceimpl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ht.dao.UserDao;
import com.ht.model.User;
import com.ht.service.UserService;
import com.ht.util.Constants;
import com.ht.util.MyPage;

@Component
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao userDaoImpl;
	
	@Override
	public List<User> findUserByExample(User user) {
		return userDaoImpl.findUserByExample(user);
	}
	
	@Override
	public boolean userExists(User user) {
		List<User> results = userDaoImpl.findUserByExample(user);
		if(results.size()!=0){
			for (User user2 : results) {
				System.out.println(user2.getId()+" "+user2.getUsername()+" "+user2.getPassword()+" "+user2.getPermission());
			}
		}
		return results.size()==0 ? false : true ;
	}

	@Override
	public void insertUser(User user) {
		userDaoImpl.insertUser(user);
	}

	UserDao userDao ;
	
	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public int addUser(User  user ){
		int result =0  ;
		User sa = userDao.getUserById(user);
		if (sa == null) {
		    result = userDao.insertToUser(user);
		} else {
			result = 2;
		}
		return result;
	}
		
	public int deleteUser(User user) {
		return userDao.deleteUser(user);
	}

	public int updateUser(User user) {
		return userDao.updateUser(user);
	}
		
	public User getUserByUsername(String name ){
		return userDao.getUserByUsername(name);
	}

	public User getUserById(User user) {
		return userDao.getUserById(user);
	}
		
	public MyPage selectByCon(User user, int curPage){
		MyPage page = new MyPage();
		List result = userDao.selectByCon(user,curPage,Constants.PAGE_SIZE) ;
		int recordCount = userDao.getRecordCount(user);
		int totalPage = (recordCount%Constants.PAGE_SIZE==0)?recordCount/Constants.PAGE_SIZE:recordCount/Constants.PAGE_SIZE+1;
		page.setResult(result);
		page.setCurPage(curPage);
		page.setRecordCount(recordCount);
		page.setTotalPage(totalPage);
		return page ;
	  }
}
